/**************************************************************************
** CuteRSS is a simple RSS/Atom client for managing RSS/Atom Feeds
**
** Copyright (C) 2010 Prakash Nadar <prakash.nadar@gmail.com>
**
** This program is free software: you can redistribute it and/or modify
**     it under the terms of the GNU General Public License as published by
**     the Free Software Foundation, either version 3 of the License, or
**     (at your option) any later version.
**
**     This program is distributed in the hope that it will be useful,
**     but WITHOUT ANY WARRANTY; without even the implied warranty of
**     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**     GNU General Public License for more details.
**
**     You should have received a copy of the GNU General Public License
**     along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "rssfeeddatamodel.h"
#include "rssdata.h"
#include "feedfetcher.h"
#include <QFont>
#include <QBrush>
#include <QTimer>

#include <QDebug>

RssFeedDataModel::RssFeedDataModel(QString url, QObject *parent) :
    QAbstractListModel(parent)
{
    mManager = new FeedFetcher();
    connect(mManager,SIGNAL(xmlFetched(RssFetchData*)),SLOT(xmlDataAvailable(RssFetchData*)));
    mManager->setUrl(url);
    mManager->readFeeds();

    mTimer = new QTimer(this);
    this->connect(mTimer,SIGNAL(timeout()),SLOT(timeout()));
    mTimer->setInterval(1000 * 5*60); // 5 Mintues
    mTimer->start();
}

int RssFeedDataModel::rowCount(const QModelIndex & parent) const
{
    return mItems.count();
}

QVariant RssFeedDataModel::data(const QModelIndex & index, int role) const
{
    if (index.row() < 0 || index.row() > mItems.count())
        return QVariant();

    RssItemData* item = mItems[index.row()];

    if (role == Qt::DisplayRole) {
        if(index.column() == 0) {
            return item->mTitle;
        }
        else if(index.column() == 1) {
            return item->mPubDate;
        }
    }
    if  (role == Qt::BackgroundRole) {
        if(index.row() % 2) {
            return QBrush(QColor(240,240,240)) ;
        }
    }
    else if (role == Qt::FontRole && item->mRead == false) {
        QFont f;
        f.setBold(true);
        return f;
    }
    else if (role == Qt::UserRole) {
        return QVariant::fromValue<RssItemData*>(item);
    }

    return QVariant();
}

bool RssFeedDataModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (index.row() < 0 || index.row() > mItems.count())
        return false;

    if (role == Qt::UserRole) {
        //Kinda hacky, we don't really do anything to the data just emit that it has changed.
        dataChanged(index,index);
    }
}

int RssFeedDataModel::columnCount ( const QModelIndex & parent) const
{
    return 2;
}

QVariant RssFeedDataModel::headerData(int section, Qt::Orientation orientation,int role) const
{
    if(role == Qt::DisplayRole) {
        if(section == 0){
            return QString("Headline");
        }
        if(section == 1) {
            return QString("Pub Date");
        }
    }
    return QVariant();
}

//TODO: Merge data with the model items rather than just assigning it.
void RssFeedDataModel::xmlDataAvailable(RssFetchData* data)
{
   mergeFeedData(data);
   emit dataChanged(index(0),index(mItems.count() - 1));
}

void RssFeedDataModel::mergeFeedData(RssFetchData* data)
{
    RssItems newItems;
    int i, j;
    for(i = 0 ; i < data->items.count(); i++) {
        int found = false;
        for(j = 0 ; j < mItems.count(); j++) {
            if(mItems.at(j)->mLink == data->items.at(i)->mLink) {
                found = true;
                break;
            }
        }
        if(found == false) {
            //No match so add it to the list.
            newItems.append(data->items[i]);
        } else {
            break; //the rest of the items are probably old items
        }
    }
    for(i = newItems.count() - 1; i >= 0 ; i--) {
        mItems.prepend(newItems[i]);
    }
    qDebug() << mManager->url() << ": " << newItems.count() << " New items";
}

void RssFeedDataModel::setUrl(QString url)
{
    mManager->setUrl(url);
}

void RssFeedDataModel::timeout()
{
    mManager->readFeeds();
}
